package com.train.mgr.modules.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.train.common.utils.AuthUtils;
import com.train.mgr.modules.system.dto.request.PostWeightDTO;
import com.train.mgr.modules.system.dto.response.PostWeightProjDTO;
import com.train.mgr.modules.system.entity.PostWeight;
import com.train.mgr.modules.system.mapper.PostWeightMapper;
import com.train.mgr.modules.system.service.IPostWeightService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 岗位重要性 服务实现类
 * </p>
 *
 * @author cxg
 * @date 2024-06-19
 */
@Slf4j
@Service("postWeightService")
public class PostWeightServiceImpl extends ServiceImpl<PostWeightMapper, PostWeight> implements IPostWeightService {

    @Autowired
    private PostWeightMapper postWeightMapper;

    public List<PostWeightProjDTO> selectGroupByCateId(Long customerId, Long postId){
        return postWeightMapper.selectGroupByCateId(customerId,postId);
    }

    public void saveOrUpdatePostWeight(Long postId,Long customerId ,List<PostWeightDTO> postWeight){
        if(CollectionUtil.isEmpty(postWeight)){
            log.info("岗位重要性选择职能信息为空～");
            return ;
        }

        //如果是更新先删除其之前建立的关系
        LambdaQueryWrapper<PostWeight> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.in(PostWeight::getCustomerId, customerId);
        queryWrapper.in(PostWeight::getPostId, postId);
        postWeightMapper.delete(queryWrapper);

        for(PostWeightDTO weight : postWeight ){
            Integer weigthType = weight.getWeightType();
            Long categoryId = weight.getCategoryId();
            List<Long> projectIdList = weight.getProjectIdList();
            if(CollectionUtil.isNotEmpty(projectIdList)){
                for(int i=0;i<projectIdList.size();i++){
                    Long projectId = projectIdList.get(i);

                    PostWeight bean = new PostWeight();
                    bean.setCustomerId(customerId);
                    bean.setPostId(postId);
                    bean.setWeightType(weigthType);
                    bean.setProjectId(projectId);
                    bean.setCategoryId(categoryId);
                    bean.setCreateBy(AuthUtils.getUserId().toString());
                    postWeightMapper.insert(bean);
                }
            }
        }
    }

}
